"use client";

import Link from "next/link";
import Image from "next/image";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Product } from "@/types/Product";
import { PageBackground } from "@/components/ui/page-background";
import { Slider } from "@/components/ui/slider";
import { Label } from "@/components/ui/label";
import { useUIPreferences } from "@/contexts/UIPreferencesContext";
import { getProducts } from "@/lib/api";
import { useEffect, useState } from "react";

const categories = ['电脑外设', '电脑硬件', '移动设备'];

export default function HomePage() {
  const { getOpacity, setOpacity } = useUIPreferences();
  const [products, setProducts] = useState<Product[]>([]);
  const [error, setError] = useState<string | null>(null);
  const homeOpacity = getOpacity('home');

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const data = await getProducts();
        setProducts(data);
      } catch (err: any) {
        setError("无法加载商品列表。请检查后端服务是否正在运行。");
      }
    };
    fetchProducts();
  }, []);

  return (
    <>
      <PageBackground src="/images/backgrounds/home.jpg" opacity={homeOpacity} />

      <div className="fixed bottom-4 right-4 z-50 w-48 rounded-lg border bg-background/80 p-4 shadow-lg backdrop-blur-sm">
        <Label htmlFor="opacity-slider" className="mb-2 block text-sm font-medium">背景不透明度</Label>
        <Slider
          id="opacity-slider"
          min={0}
          max={1}
          step={0.05}
          value={[homeOpacity]}
          onValueChange={(value) => setOpacity('home', value[0])}
        />
      </div>

      <div className="relative z-10">
        <section className="container mx-auto px-4 pt-16 pb-12 text-center">
          <h1 className="text-4xl md:text-5xl font-bold tracking-tighter">发现您下一个心仪好物</h1>
          <p className="mx-auto mt-4 max-w-[700px] text-lg text-muted-foreground">
            我们精心评测并推荐最优质的商品，让您购物无忧。
          </p>
          <div className="mt-6">
            <Link href="#products">
              <Button size="lg">浏览所有商品</Button>
            </Link>
          </div>
        </section>

        <section id="products" className="container mx-auto p-4">
          {error && <p className="text-center text-destructive">{error}</p>}
          <div className="space-y-12">
            {categories.map((category) => (
              <section key={category}>
                <h2 className="text-3xl font-bold mb-6">{category}</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                  {products
                    .filter(product => product.category === category)
                    .map((product) => (
                      <Card key={product.id} className="group flex flex-col overflow-hidden border transition-all duration-300 ease-in-out hover:shadow-lg hover:border-primary bg-background/80 backdrop-blur-sm">
                        <CardHeader className="p-0">
                          <div className="relative w-full aspect-video overflow-hidden">
                            <Image 
                              src={product.imageUrl} 
                              alt={product.name} 
                              fill
                              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                              style={{objectFit: 'cover'}}
                              className="rounded-t-lg transition-transform duration-500 ease-in-out group-hover:scale-110"
                            />
                          </div>
                        </CardHeader>
                        <div className="p-4 flex flex-col flex-grow">
                          <CardTitle className="text-lg">{product.name}</CardTitle>
                          <CardDescription className="text-sm text-gray-400 mt-1">{product.category}</CardDescription>
                          <CardContent className="p-0 pt-4 flex-grow">
                             {/* Truncate long descriptions */}
                            <p className="text-sm text-gray-300 line-clamp-2">{product.description}</p>
                          </CardContent>
                          <CardFooter className="p-0 pt-4 flex justify-between items-center">
                              <span className="text-xl font-semibold text-cyan-400">¥{product.price.toFixed(2)}</span>
                              <Link href={`/products/${product.id}`} passHref>
                                  <Button>查看详情</Button>
                              </Link>
                          </CardFooter>
                        </div>
                      </Card>
                    ))}
                </div>
              </section>
            ))}
          </div>
        </section>
      </div>
    </>
  );
}
